import pandas as pd
import akshare as ak


def fetch_stock_data(stock_code):
    """
    获取指定股票代码的最近 30 天数据。

    参数:
        stock_code (str): 股票代码，例如 "sh600000" 或 "sz000001"

    返回:
        pd.DataFrame: 包含最近 30 天数据的 DataFrame。如果发生错误或没有数据，返回 None。
    """
    try:
        # 获取当前时间
        end_date = pd.Timestamp.now()
        start_date = end_date - pd.Timedelta(days=30)

        # 直接获取最近 30 天的数据
        stock_df = ak.stock_zh_a_daily(symbol=stock_code, adjust="qfq")

        # 检查是否成功获取到数据
        if stock_df.empty:
            print(f"警告：无法获取 {stock_code} 的历史数据，请检查股票代码或网络连接。")
            return None

        # 将日期列转换为 datetime 类型
        stock_df['date'] = pd.to_datetime(stock_df['date'])

        # 筛选最近 30 天的数据
        recent_data = stock_df[(stock_df['date'] >= start_date) & (stock_df['date'] <= end_date)]

        # 检查筛选后是否有数据
        if recent_data.empty:
            print(f"提示：{stock_code} 在最近 30 天内没有交易数据。")
            return None

        # 返回最近 30 天的数据
        return recent_data

    except KeyError as e:
        print(f"错误：数据格式不正确，缺失必要字段：{e}")
        return None
    except Exception as e:
        print(f"发生未知错误：{e}")
        return None


def format_stock_data_with_headers(data):
    """
    将股票数据格式化为带汉字标题的逗号分隔文本集合，并将换手率保留三位小数。

    参数:
        data (pd.DataFrame): 包含股票数据的 DataFrame

    返回:
        list: 包含每一天数据的带汉字标题的逗号分隔文本的列表
    """
    # 用于存储每天的文本数据
    text_list = []

    # 定义汉字标题
    headers = [
        "数据时间", "开盘价", "最高价", "最低价", "收盘价",
        "成交量", "成交额", "振幅", "涨跌幅", "涨跌额", "换手率"
    ]

    # 将标题拼接为一行
    header_line = ",".join(headers)
    text_list.append(header_line)

    # 遍历每一天的数据
    for _, row in data.iterrows():
        # 格式化换手率，保留三位小数
        turnover = row['turnover'] if 'turnover' in row else None
        turnover_formatted = f"{turnover:.3f}%" if turnover is not None else "N/A"

        # 格式化文本为带汉字标题的逗号分隔字符串
        text = (
            f"{row['date'].strftime('%Y-%m-%d')},"
            f"{row['open']:.2f},"
            f"{row['high']:.2f},"
            f"{row['low']:.2f},"
            f"{row['close']:.2f},"
            f"{row['volume']},"
            f"{row['amount']:.2f},"
            f"{(row['high'] - row['low']) / row['low'] * 100:.2f}%,"
            f"{(row['close'] - row['open']) / row['open'] * 100:.2f}%,"
            f"{row['close'] - row['open']:.2f},"
            f"{turnover_formatted}"
        )
        text_list.append(text)

    return text_list

# 示例调用
if __name__ == "__main__":
    stock_code = "sh600000"  # 替换为实际的股票代码
    data = fetch_stock_data(stock_code)

    if data is not None:
        # 将数据格式化为带汉字标题的逗号分隔文本集合
        text_list = format_stock_data_with_headers(data)
        print("------------提示：将以下文本内容给到复制给DeepSeek，让AI做智能分析 ------------")
        print("我的股票代码"+stock_code+"，帮我分析股票风险情况、压力位、仓位建议，数据如下：")
        # 输出文本内容
        for text in text_list:
            print(text)
        print("通过量化分析方法进行分析，包括趋势筛选、结合量价指标和波动特征、基于收盘价特征判断、根据波动率动态调整等")
        print("------------------------------------文本内容结束------------------------------------")